#include "xiaoglwidget.h"

extern const char *vertexShaderCode;
extern const char *fragmentShaderCode;


xiaoGLWidget::xiaoGLWidget(QWidget *parent): m_program(this), m_indexBuf(QOpenGLBuffer::IndexBuffer)
{
}

xiaoGLWidget::~xiaoGLWidget()
{
    m_vertexBuf.destroy();
    m_indexBuf.destroy();
}

void xiaoGLWidget::initializeGL()
{
    initializeOpenGLFunctions();
    installShader();
    sendDataToOpenGL();

    glEnable(GL_DEPTH_TEST);
}

void xiaoGLWidget::paintGL()
{
//    initializeOpenGLFunctions();
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    m_program.bind();
    m_vertexBuf.bind();
    m_indexBuf.bind();
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);
    m_vertexBuf.release();
    m_indexBuf.release();
    m_program.release();
}

void xiaoGLWidget::resizeGL(int w, int h)
{
}

void xiaoGLWidget::sendDataToOpenGL()
{
    initializeOpenGLFunctions();
    const GLfloat RED_TRIANGLE_DEPTH = -0.5f;
    const GLfloat BLUE_TRIANGLE_DEPTH = 0.5f;
    GLfloat verts[] =
    {
        +0.0f, -1.0f, RED_TRIANGLE_DEPTH,
            +1.0f, +0.0f, +0.0f,
            +1.0f, +1.0f, RED_TRIANGLE_DEPTH,
            +1.0f, +0.0f, +0.0f,
            -1.0f, +1.0f, RED_TRIANGLE_DEPTH,
            +1.0f, +0.0f, +0.0f,

            +0.0f, +1.0f, BLUE_TRIANGLE_DEPTH,
            +0.0f, +0.0f, +1.0f,
            -1.0f, -1.0f, BLUE_TRIANGLE_DEPTH,
            +0.0f, +0.0f, +1.0f,
            +1.0f, -1.0f, BLUE_TRIANGLE_DEPTH,
            +0.0f, +0.0f, +1.0f,
        };

    GLuint indices[] = {0, 1, 2, 3, 4, 5};

    this->m_vertexBuf.create();
    this->m_indexBuf.create();

    this->m_vertexBuf.bind();
    this->m_indexBuf.bind();

    this->m_vertexBuf.allocate(verts, sizeof(verts));
    this->m_indexBuf.allocate(indices, sizeof(indices));

    m_program.enableAttributeArray(0);
    m_program.setAttributeBuffer(0, GL_FLOAT, 0, 3, sizeof(float) * 6);

    m_program.enableAttributeArray(1);
    m_program.setAttributeBuffer(1, GL_FLOAT, sizeof(float) * 3, 3, sizeof(float) * 6);

    m_vertexBuf.release();
    m_indexBuf.release();
    m_program.release();
}

void xiaoGLWidget::installShader()
{
    QOpenGLShader vertexShader(QOpenGLShader::Vertex);
    vertexShader.compileSourceCode(vertexShaderCode);
    QOpenGLShader fragmentShader(QOpenGLShader::Fragment);
    fragmentShader.compileSourceCode(fragmentShaderCode);

    m_program.addShader(&vertexShader);
    m_program.addShader(&fragmentShader);
    m_program.link();
    m_program.bind();
}
